//
// Created by bigknife on 14-9-7.
// Copyright (c) 2014 51fmzg. All rights reserved.
//


#import "IDLTaskButton.h"

@interface IDLTaskButton()
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic) NSInteger updateCounter;
@end
@implementation IDLTaskButton {

}
- (void) _init {
	self.callbackTi = 1;
	self.counterMax = 100;
}
- (id)initWithFrame:(CGRect)frame {
	self = [super initWithFrame:frame];
	if (self) {
		[self _init];
	}

	return self;
}

- (id)initWithCoder:(NSCoder *)coder {
	self = [super initWithCoder:coder];
	if (self) {
		[self _init];
	}

	return self;
}

- (void)startTask {
    if (![self.delegate shouldStartTaskForTaskButton:self]) {
        return;
    }
    
	self.userInteractionEnabled = NO;
	self.timer = [NSTimer timerWithTimeInterval:self.callbackTi
										 target:self
									   selector:@selector(updateAndCallback)
									   userInfo:nil
										repeats:YES];
	[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
	[self.delegate didStartTaskForTaskButton:self];

}

- (void)endTask {
	self.userInteractionEnabled = YES;
	[self.timer invalidate];
	self.timer = nil;
	self.updateCounter = 0;
	[self.delegate didEndTaskForTaskButton:self];

}
-(void) updateAndCallback {
	self.updateCounter ++;
	if(self.updateCounter < self.counterMax){
		[self.delegate taskButton:self updatedTo:(self.updateCounter)];
	}else{
		[self endTask];
	}

}

@end